package com.kgd.news.controller.admin;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.upload.UploadFile;
import com.kgd.news.entity.News;
import com.kgd.news.entity.Question;
import com.kgd.news.utils.BaseController;
import com.kgd.news.utils.StringUtils;

/**
 * @Email: huangsanm@foxmail.com
 * @Date: 2017/10/8
 * @Time: 下午4:28
 */
public class QuestionController extends BaseController {


    @Override
    public void list() {
        String title = getPara("title");
        String type = getPara("type");
        String isbanner = getPara("isbanner");
        String sql = "from question where 1 = 1";
        String querytype = "question";
        if (!StringUtils.isEmpty(title)) {
            sql += " and title like '%" + title + "%'";
            querytype += title;
        }
        if (!StringUtils.isEmpty(type)) {
            if ("-1".equals(type)) {
                sql += " and type is null" ;
            } else {
                sql += " and type =" + type;

            }
            querytype += type;
        }
        if (!StringUtils.isEmpty(isbanner)) {
            sql += " and isbanner = " + isbanner;
            querytype += isbanner;
        }
        sql += " order by id desc";
        Page<Question> data = Question.dao.paginate(getPageIndex(querytype), PAGE_SIZE, "select *", sql);
        setAttr("data", data);
        setAttr("isbanner", isbanner);
        setAttr("type", type);
        render("question_list.html");
    }

    @Override
    public void edit() {
        Integer id = getParaToInt("id");
        Question dict = Question.dao.findById(id);

        setAttr("question", dict);
        setAttr("type",getPara("type"));
        if (dict != null) {
//            setAttr("isbanner", dict.getIsbanner());
        }
        render("question_edit.html");
    }

    @Override
    public void save() {
        UploadFile uploadFile = getFile("img");
        String filePath = "";
        if (uploadFile != null && !StringUtils.isEmpty(uploadFile.getFileName())) {
            filePath = getFileUploadPath(uploadFile);
        }

        UploadFile uploadFile1 = getFile("banner");
        String filePath1 = "";
        if (uploadFile1 != null && !StringUtils.isEmpty(uploadFile1.getFileName())) {
            filePath1 = getFileUploadPath(uploadFile1);
        }
        Question sd = getModel(Question.class, "question");
        if (!StringUtils.isEmpty(filePath)) {
            sd.setImg(filePath);
        }
        if (!StringUtils.isEmpty(filePath1)) {
            sd.setBanner(filePath1);
        }

        if(sd != null && sd.getId() != null){
            sd.update();
        }else{
            sd.save();
        }

        list();
    }

    @Override
    public void del() {
        String ids = getPara("ids");
        Db.update("delete from question where id in (" + ids + ")");
        setAttr("type",getPara("type"));
        list();
    }
}
